<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-submit>
            <el-button :disabled="canSubmit" @click="submit()">提交</el-button>
          </template>
          <template v-slot:filter-excel>
            <el-button @click="exportExcel()">导出excel</el-button>
          </template>
          <template v-slot:filter-print>
            <el-button @click="print()">打印</el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('assetMoveDepot:details')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo }}</span
          >
          <span v-else>{{ scope.row.orderNo }}</span>
        </template>
      </table-container>
    </div>

    <asset-transfer-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :order-id="modifyInfo.orderId"
      @returnModify="returnModify"
    />

    <!-- 详情 -->
    <detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :order-id="detailInfo.orderId"
      @returnBack="getList"
    />
    <!-- 偏好设置 -->
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <!-- 高级搜索 -->
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <!-- 明细 -->
    <detailsList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailsList>
    <!-- 导出 -->
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="assetMoveDepot">
import AssetTransferModify from './modify'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import {
  assetMoveDepotCustomizeListPage,
  deleteAssetMoveDepot,
  rejectAssetMoveDepot,
  revokeAssetMoveDepot,
  submitAssetMoveDepott,
  moveAssetMoveDepot,
  checkAssetMoveDepot,
  cancelAssetMoveDepot,
  assetMoveDepotPrintList,
  assetMoveDepotExcel,
  refuseAssetMoveDepot,
  cancelAuditAssetMoveDepot,
} from '@/api/asset'
import { getBusinessKeyById } from '@/api/flowable'
import detailsList from './detailsList'
import detail from './details'
import { fatchTemplateByCode } from '@/api/base'
import { getDepotAll } from '@/api/core'

const { proxy } = getCurrentInstance()

//导出提示相关配置
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('assetMoveDepot:add'),
    },
    {
      type: 'slot',
      value: 'submit',
      show: proxy.$permission('assetUseExportOrder:submit'),
    },
    {
      type: 'slot',
      value: 'excel',
      show: proxy.$permission('assetMoveDepot:exportOrder'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('assetMoveDepot:printOrder'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      //状态: 待提交:1, 待审批:2, 审批中:3, 已驳回:4, 已拒绝：5, 完成：6
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('assetMoveDepot:submit'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 4
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('assetMoveDepot:update'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 4
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('assetMoveDepot:delete'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 4
        },
      },
      {
        label: '批准',
        event: check,
        show: proxy.$permission('assetMoveDepot:check'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('assetMoveDepot:reject'),
        ifRender: checkIfRenderBtnFlow,
      },

      {
        label: '拒绝',
        event: refuse,
        show: proxy.$permission('assetMoveDepot:refuse'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '销审',
        event: salesReview,
        show: proxy.$permission('assetMoveDepot:salesReview'),
        ifRender: checkIfRenderSalesReview,
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('assetMoveDepot:revoke'),
        ifRender: function (row) {
          return (
            row.status === 2 ||
            (row.status === 6 &&
              proxy.$store.state.permission.systemConfig
                .allow_asset_move_depot_approval_type == 0)
          )
        },
      },
    ],
  },
})
const modifyInfo = ref({ visible: false, orderId: '', title: '' })
const detailListInfo = ref({ visible: false })
const detailInfo = ref({ visible: false, orderId: '' })
const preferenceInfo = ref({ visible: false })
const advancedSearchInfo = ref({ visible: false, data: {} })
const clearType = ref(true)
const slipSelectRequest = ref(true)
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
// 批量审批（选中的数据全是未提交或者全是已驳回）
const canSubmit = computed(() => {
  if (
    tableInfo.value.selections.length === 0 ||
    !proxy.$permission('assetUseExportOrder:submit')
  ) {
    return true
  }
  const statusArr = [1, 4]
  const tempBool = tableInfo.value.selections.some((item) => {
    if (!statusArr.includes(item.status)) {
      return true
    }
  })
  return tempBool
})
watch(
  () => proxy.$router.currentRoute.value.name,
  (to, from) => {
    if (!from) return
    if (
      from.includes('myPendingDetail') ||
      from.includes('myFinishedDetail') ||
      from.includes('myApplyDetail')
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)

// 批准/驳回/拒绝
function checkIfRenderBtnFlow(row) {
  return (
    row.status === 2 &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_move_depot_approval_type == 1
  )
}
// 销审
function checkIfRenderSalesReview(row) {
  return (
    proxy.$store.state.permission.systemConfig
      .allow_asset_move_depot_approval_type !== 0 && row.status === 6
  )
}
setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'asset_move_depot_order_status',
      show: false,
      hidden: true,
    },
    exportDepotName: {
      label: '出库仓库',
      value: 'exportDepotName',
      asValue: 'exportDepotId',
      componentType: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '2',
      },
      api: getDepotAll,
      show: false,
      hidden: true,
    },
    storeDepotName: {
      label: '入库仓库',
      value: 'storeDepotName',
      asValue: 'storeDepotId',
      componentType: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '2',
      },
      api: getDepotAll,
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function handleClose() {
  dialogInfo.value.visible = false
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  await getList()
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  clearType.value = !clearType.value
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//展示明细
function showDetail(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'assetMoveDepot',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        detailInfo.value.orderId = row.id
        detailInfo.value.visible = true
      }
    }
  })
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetAssetMoveDepotOrder-com.slip.spd.entity.vo.asset.assetPoolManage.AssetMoveDepotOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = assetMoveDepotCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
//新增
function create() {
  modifyInfo.value.orderId = ''
  modifyInfo.value.title = '新增资产移库'
  modifyInfo.value.visible = true
}
//修改
function update(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'assetMoveDepot',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        modifyInfo.value.orderId = row.id
        modifyInfo.value.title = '修改资产移库'
        modifyInfo.value.visible = true
      }
    }
  })
}
//提交
function submit(row = undefined) {
  let ids = []
  if (row) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'assetMoveDepot',
    orderIds: ids,
  }
  submitAssetMoveDepott(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//删除
function remove(row) {
  const data = []
  data.push(row.id)
  deleteAssetMoveDepot(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//批准
function check(row) {
  const data = {
    orderId: row.id,
  }
  checkAssetMoveDepot(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//拒绝
function refuse(row) {
  proxy
    .$prompt('请输入拒绝理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      refuseAssetMoveDepot(data).then((resp) => {
        if (resp) {
          getList()
        }
      })
    })
}
//销审
function salesReview(row) {
  // const data = {
  //     orderId: row.id,
  //   }
  cancelAuditAssetMoveDepot(row.id).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
//驳回
function reject(row) {
  proxy
    .$prompt('请输入驳回理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: '驳回理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      rejectAssetMoveDepot(data).then((resp) => {
        if (resp) {
          getList()
        }
      })
    })
}
//移库
function doMove(row) {
  const data = []
  data.push(row.id)
  moveAssetMoveDepot(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//取消
function doCancel(row) {
  const data = []
  data.push(row.id)
  cancelAssetMoveDepot(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//撤回
function revoke(row) {
  const data = []
  data.push(row.id)
  revokeAssetMoveDepot(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//导出Excel
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  assetMoveDepotExcel(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function print() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择当数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = true
  //打印
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'assetMoveDepot:printOrder',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag,
  }
  assetMoveDepotPrintList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function pageInfo(obj) {
  page.value = obj
}
function returnModify() {
  if (modifyInfo.value.exportId) {
    getList()
  } else {
    search()
  }
}
</script>

<style scoped></style>
